package com.steve.xfood.service.impl;

import com.steve.xfood.convert.OrderMaster2OrderDTOConverter;
import com.steve.xfood.repository.OrderDetailRepository;
import com.steve.xfood.repository.OrderMasterRepository;
import com.steve.xfood.dto.CartDTO;
import com.steve.xfood.dto.OrderDTO;
import com.steve.xfood.dataobject.OrderDetail;
import com.steve.xfood.dataobject.OrderMaster;
import com.steve.xfood.dataobject.ProductInfo;
import com.steve.xfood.enums.ResultEnum;
import com.steve.xfood.enums.OrderStatusEnum;
import com.steve.xfood.enums.PayStatusEnum;
import com.steve.xfood.exception.XFoodException;
import com.steve.xfood.service.*;
import com.steve.xfood.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author steve
 * @date 2020/5/8 6:44 上午
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private OrderDTO orderDTO;
    @Autowired
    private OrderMaster orderMaster;
    @Autowired
    private WeChatPayService weChatPayService;
    @Autowired
    private PushMessageService pushMessageService;
    @Autowired
    private WebSocket webSocket;

    /**
     * 注解@Transactional(rollbackFor = Exception.class)的意思是：
     * 让事务在遇到非RuntimeException时也回滚
     * 如果不加rollback，则事务只会在遇到RuntimeException时才回滚
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO create(OrderDTO orderDTO) {
        /** 定义orderId */
        String orderId = KeyUtil.genUniqueKey();

        /** 定义商品总价初始值 */
        BigDecimal orderAmount = new BigDecimal(0);

        //1.查询商品（库存数量，价格）
        //1.1 获取商品数据
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productInfoService.findById(orderDetail.getProductId());
            if(productInfo == null) {
                //商品不存在则抛异常
                throw new XFoodException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //2.计算商品总价((商品单价*商品购买数量)+当前总价)
            orderAmount = productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);

            //设置数据库主键唯一id
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            //订单id需要在外面定义好
            orderDetail.setOrderId(orderId);
            //把商品信息设置到订单详情中
            BeanUtils.copyProperties(productInfo, orderDetail);
            //订单详情入库
            orderDetailRepository.save(orderDetail);

            //扣库存(传统方法)
            /*List<CartDTO> cartDTOList = new ArrayList<>();
            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(),orderDetail.getProductQuantity());
            cartDTOList.add(cartDTO);
            productInfoService.decreaseStock(cartDTOList);*/
        }

        //3.写入数据库（OrderMaster和OrderDetail）
        //把dto类数据复制到数据库映射实体类OrderMaster,先设置orderId，再复制D
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        //设置订单商品总价
        orderMaster.setOrderAmount(orderAmount);
        //重新设置订单状态和支付状态的默认值
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        //4.扣库存(jdk1.8)
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.decreaseStock(cartDTOList);

        //新增订单推送消息
        webSocket.sendMessage("有新的订单");
        return orderDTO;

    }

    @Override
    public OrderDTO findOrderById(String orderId) {
        //OrderMaster orderMaster = orderMasterRepository.findOne(orderId); springboot1.5
        /**
         * 查不到返回Null
         * 使用findById(orderId).get()方法会抛异常
         */
        OrderMaster orderMaster = orderMasterRepository.findById(orderId).orElse(null);
        if(orderMaster == null) {
            //订单不存在
            throw new XFoodException(ResultEnum.ORDER_NOT_EXIST);
        }
        //把数据库的订单主表信息设置到orderDTO中
        BeanUtils.copyProperties(orderMaster,orderDTO);
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            //订单详情不存在
            throw new XFoodException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }
        //把数据库的订单详情表设置到orderDTO中
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findAll(String buyerOpenid, Pageable pageable) {
        //查询出数据库的订单主表分页数据
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);
        //通过工具类把订单主表转换到orderDTOList
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());
        //创建orderDTO分页对象
        return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO cancel(OrderDTO orderDTO) {
        //1.判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            //订单不是新订单状态
            log.info("【取消订单】订单状态不正确 订单id={}, 订单状态={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new XFoodException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //2.修改订单状态并存入数据库
        BeanUtils.copyProperties(orderDTO, orderMaster);
        //设置为已取消状态
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        //订单状态设置回OrderDTO
        orderDTO.setOrderStatus(orderMaster.getOrderStatus());
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if (result == null) {
            //修改失败
            log.info("【取消订单】更新订单失败 result={}", orderMaster);
            throw new XFoodException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            //订单详情列表为空
            log.info("【取消订单】订单详情为空 orderDTO={}", orderDTO);
            throw new XFoodException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        //3.归还库存
        //构建购物车List
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.increaseStock(cartDTOList);
        //4.如果已经付款，则需要退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            //订单支付状态=1
            weChatPayService.refund(orderDTO);
        }

        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO finished(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.info("【完结订单】订单状态不正确 订单id={}, 订单状态={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new XFoodException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if (result == null) {
            log.info("【完结订单】订单更新失败 orderMaster={}", result);
            throw new XFoodException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        //推送微信订单消息模板
        pushMessageService.orderStatus(orderDTO);
        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO paid(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.info("【支付订单】订单状态不正确 订单id={}, 订单状态={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new XFoodException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //判断订单支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.info("【支付订单】 订单支付状态不正确 订单id={}, 支付状态={}", orderDTO.getOrderId(),orderDTO.getPayStatus());
            throw new XFoodException(ResultEnum.ORDER_PAID_STATUS_FAIL);
        }

        //修改订单状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if (result == null) {
            log.info("【支付订单】订单更新失败 orderMaster={}", result);
            throw new XFoodException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findAll(Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findAll(pageable);
        //数据转换
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());
        //返回分页数据
        return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }
}
